package user

import (
	"net/http"

	pb "gitee.com/jiebaiyou/demo-grpc/protos/user/v2"
	"github.com/gin-gonic/gin"
)

func RegisterRoutes(r *gin.Engine, c *Client) {
	user := r.Group("/user")
	{
		user.POST("/create", handleCreate(c))
		user.GET("/get", handleGet(c))
	}
}

func handleCreate(c *Client) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var req pb.CreateRequest
		if err := ctx.BindJSON(&req); err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		resp, err := c.Create(ctx, &req)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		ctx.JSON(http.StatusOK, resp)
	}
}

func handleGet(c *Client) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var req pb.GetRequest
		if err := ctx.BindQuery(&req); err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		resp, err := c.Get(ctx, &req)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		ctx.JSON(http.StatusOK, resp)
	}
}
